/**
 * 
 */
package com.iss.card.model;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.text.TextUtils;
import android.util.Log;

import com.iss.card.R;
import com.iss.card.common.CommonValue;
import com.iss.card.common.Tools;
import com.iss.card.common.UtilityHelper;
import com.iss.card.view.model.CityBean;
import com.iss.card.view.model.ResponseBean;
import com.iss.card.view.overrideview.ParticipatorSortUtils;
import com.iss.card.webservice.BaseModel;
import com.iss.card.webservice.WebServiceAsyncService;
import com.iss.card.webservice.WebServiceAsyncService.Operation;
import com.iss.card.webservice.WebServiceAsyncService.PostExecute;
import com.iss.card.webservice.WebServiceAsyncServiceHelper;
import com.iss.card.webservice.WebServiceManager.WebServiceRegistrationParameter;
import com.iss.card.webservice.WebServiceManager.WebServiceUrlPortManager;
import com.iss.card.webservice.WebServiceUtils;

/**
 * @author dtdh
 * 
 */
public class CityDataManager {

	/** city id for all in country. */
	public final static String CITY_ID_ALL = "-1";
	/** invalid city id. it is used for those city not registered in server. */
	public final static String CITY_ID_INVALID = "-2";
	private final static String TAG = CityDataManager.class.getSimpleName();
	private final static String SP_KEY_RECENTLY_LOCATED_CITYS = "SP_KEY_RECENTLY_LOCATED_CITYS";
	private final static String SP_CITY_SEPERATOR = "@#@";
	private final static String SP_CITY_DETAIL_SEPERATOR = "@###@";
	private final static int RECENTLY_LOCATED_CITY_MAX_NUM = 2;

	private static CityDataManager sInstance;
	private Context mContext;

	private List<CityBean> mCityList = new ArrayList<CityBean>();

	private CityDataManager() {

	}

	public synchronized static CityDataManager instance() {
		if (sInstance == null) {
			sInstance = new CityDataManager();
		}
		return sInstance;
	}

	public void initialize(Context ct) {
		mContext = ct;
		requestGetCityList();
	}

	public List<CityBean> getCityList() {
		return mCityList;
	}

	public List<CityBean> getRecentlyLocatedCity() {
		return readRecentlyCityRawData();
	}

	public void saveRecentlyLocatedCity(CityBean city) {
		List<CityBean> list = readRecentlyCityRawData();
		list.remove(city);

		final int num = list.size();
		List<CityBean> newList = new ArrayList<CityBean>();
		newList.add(city);
		final int dataMaxNum = (num < RECENTLY_LOCATED_CITY_MAX_NUM) ? num
				: num - 1;
		for (int i = 0; i < dataMaxNum; ++i) {
			CityBean info = list.get(i);
			newList.add(info);
		}

		writeRecentlyCityRawDatas(newList);
	}

	public CityBean findCityInfoByCityName(String name) {
		CityBean city = new CityBean();
		if (TextUtils.isEmpty(name)) {
			city.setCityId(CITY_ID_ALL);
			city.setCityName(mContext.getResources().getString(R.string.store_list_view_city_all));
			city.setStoreNumber("0");
			city.setIsHot(false);
		} else {
			List<CityBean> _list = mCityList;
			for (CityBean info : _list) {
				Log.d(TAG, "findCityInfoByCityName: " + info.getCityName() + ", " + name);				
				if (info.getCityName().startsWith(name)) {
					return info;
				}
			}			
			city.setCityId(CITY_ID_INVALID);
			city.setCityName(name);
			city.setStoreNumber("0");
			city.setIsHot(false);
		}
		return city;
	}

	private void writeRecentlyCityRawDatas(List<CityBean> list) {
		SharedPreferences sp = UtilityHelper.instance().getSharedPreferences(
				CommonValue.SP_CONFIG);
		Editor ed = sp.edit();
		StringBuffer builder = new StringBuffer();
		Iterator<CityBean> it = list.iterator();
		while (it.hasNext()) {
			CityBean info = it.next();
			builder.append(info.getCityId() + SP_CITY_DETAIL_SEPERATOR
					+ info.getCityName() + SP_CITY_DETAIL_SEPERATOR
					+ info.getIsHot() + SP_CITY_DETAIL_SEPERATOR
					+ info.getJianpin() + SP_CITY_DETAIL_SEPERATOR
					+ info.getStoreNumber());
			builder.append(it.hasNext() ? SP_CITY_SEPERATOR : "");
		}
		ed.putString(SP_KEY_RECENTLY_LOCATED_CITYS, builder.toString());
		ed.commit();
	}

	private List<CityBean> readRecentlyCityRawData() {
		SharedPreferences sp = UtilityHelper.instance().getSharedPreferences(
				CommonValue.SP_CONFIG);
		String[] citys = sp.getString(SP_KEY_RECENTLY_LOCATED_CITYS, "").split(
				SP_CITY_SEPERATOR);
		List<CityBean> cityList = new ArrayList<CityBean>();
		for (String item : citys) {
			String[] details = item.split(SP_CITY_DETAIL_SEPERATOR);
			if (details.length < 5) {
				continue;
			}

			CityBean city = new CityBean();
			city.setCityId(details[0]);
			city.setCityName(details[1]);
			city.setIsHot(Boolean.valueOf(details[2]));
			city.setJianpin(details[3]);
			city.setStoreNumber(details[4]);
			cityList.add(city);
		}
		return cityList;
	}

	/**
	 * get city info from server.
	 */
	private void requestGetCityList() {
		Log.d(TAG, "requestGetCityList");
		WebServiceAsyncService service = new WebServiceAsyncService();
		service.setParameterToAsyncService(mContext, service.getNextToken(),
				Operation.OP_SERVICE_ARG_GET_CITYLIST,
				WebServiceRegistrationParameter.CITY_LIST_PARAMETER,
				new String[] {},
				WebServiceUrlPortManager.ACTION_URL_PORT_CITYLIST, null,
				WebServiceAsyncServiceHelper.TYPE_HTTP_GET_INSTREAM);
		service.setPostExecute(new PostExecute() {
			@Override
			public void onAsyncServiceComplete(int token, Object result,
					int index) {
				ResponseBean response = WebServiceUtils
						.getObjectResultToBaseInfo(result, CityBean.class);
				if (Tools.onPostCheck(mContext, response)) {
					return;
				}

				responseGetCityList(response);
			}
		});
	}

	/**
	 * get city list.
	 */
	private void responseGetCityList(ResponseBean response) {
		if (response == null) {
			return;
		}

		List<? extends BaseModel> list = response.getReturnList();
		mCityList.clear();

		for (BaseModel info : list) {
			mCityList.add((CityBean) info);
		}
		ParticipatorSortUtils.computeClerkModelSort(mCityList);
	}
}
